import React,{ useEffect, useState } from 'react';
import { Modal, Form, Input, Button } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { DeviceListItem } from '../data';

interface CreateFormProps {
  modalVisible: boolean;
  loading:boolean;
  onSubmit: (values: DeviceListItem) => void;
  onCancel: () => void;
  values:DeviceListItem;
}

// const { Option } = Select;

const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

const formRef = React.createRef<FormInstance>();
let oldValue = "";
const DeviceRenameDialog: React.FC<CreateFormProps> = (props) => {
  const { modalVisible, loading, onSubmit, onCancel, values } = props;
  const [disabled, handleDisabled] = useState<boolean>(true);
  const [form] = Form.useForm();

  const handleFinish = (values: { [key: string]: any }) => {
    if (onSubmit) {
      onSubmit(values as DeviceListItem);
    }
  };

  const handleUpdate = () => {
    if (!form) return;
    form.submit();
  };

  useEffect(() => {
    if(modalVisible){
      if(values && values.id){
        form.setFieldsValue(values);
        oldValue = values.name;
      }
    }
    handleDisabled(true);
  },[modalVisible]);

  const onchange = (e :Event) =>{
    const newValue = e.target.value;
    newValue == oldValue ? handleDisabled(true):handleDisabled(false);
  }

  const renderContent = () => {
    return (
      <>
        <Form.Item name="id" style={{ display: 'none' }}></Form.Item>
        <Form.Item
          name="name"
          label="设备名称"
          rules={[{ required: true, max: 32, whitespace: true }]}
        >
          <Input placeholder="请输入设备名称" style={{ width: 200 }} onChange={onchange}/>
        </Form.Item>
      </>
    );
  };

  return (
    <Modal
      destroyOnClose
      width={400}
      title="设备重命名"
      visible={modalVisible}
      // {...modalFooter}
      onCancel={onCancel}
      footer={[
        <Button key="cancel" onClick={onCancel}>取消</Button>,
        <Button type="primary" loading={loading} disabled={disabled} onClick={handleUpdate}>确定</Button>
      ]}
    >
      <Form {...layout} ref={formRef} form={form} onFinish={handleFinish}>
        {renderContent()}
      </Form>
    </Modal>
  );
};

export default DeviceRenameDialog;
